﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace NMigrate
{
	public class BatchFileHandler : FileHandler, IHasOutput
	{
		
		public BatchFileHandler()
		{
			HasOutput.ConfigDefault(this);
		}
		#region FileHandler Members

		public override string Extension
		{
			get
			{
				return "bat";
			}
		}

		public override void Execute(System.IO.FileInfo file, Configuration args)
		{
			var process = new Process();
			process.StartInfo.FileName = file.FullName;
			process.StartInfo.RedirectStandardOutput = true;
			process.StartInfo.RedirectStandardError = true;
			process.StartInfo.UseShellExecute = false;
			bool error = false;
			process.ErrorDataReceived += (s, e) =>
			{
				if(Error != null)
					Error.WriteLine(e.Data);
				if(e.Data != null)
					error = true;
			};

			process.OutputDataReceived += (s, e) =>
			{
				if(Out != null)
					Out.WriteLine(e.Data);
			};

			process.Start();
			process.BeginOutputReadLine();
			process.BeginErrorReadLine();
			process.WaitForExit();
			if(process.ExitCode != 0)
				throw new Exception("Error when executing bat " + file.Name + " exit code " + process.ExitCode);
			if(error)
				throw new Exception("Error recieved on the Error output of " + file.Name);
		}


		public TextWriter Out
		{
			get;
			set;
		}

		public TextWriter Error
		{
			get;
			set;
		}

		#endregion


		#region FileHandler Members


		public override bool IsTemplated(FileInfo file)
		{
			return true;
		}

		#endregion
	}
}
